#include "BitPrinter.h"
#include <iostream>
#include <fstream>

using namespace std;

BitPrinter::BitPrinter(){
    
    buffer = 0x00000000;
    counter = 0;
    bufferSize = sizeof(unsigned int)*8;

}

int BitPrinter::clear(){
    
    buffer = 0x00000000;
    counter = 0;
}

int BitPrinter::flushBuffer(ofstream &oFile){
    
    /*Escribo el buffer en el archivo.*/
    
    oFile.write((char*)&buffer,sizeof(unsigned int));
    
    BitPrinter::clear();
}

int BitPrinter::printTRUE(ofstream &oFile){
    
    /*Hago un buffer OR 1 (setearía el ultimo bit en uno)
     y shiffteo un bit a la izquierda rellenando con un cero
     a la derecha.*/
   
    buffer <<= 1;
    
    buffer |= 0x00000001;
    
    counter ++;
     
    if(counter == bufferSize) BitPrinter::flushBuffer(oFile);
    
    return 0;
}

int BitPrinter::printFALSE(ofstream &oFile){
    
    buffer <<= 1;
    
    counter ++;
     
    if(counter == bufferSize) BitPrinter::flushBuffer(oFile);    
    
    return 0;
}

int BitPrinter::close(ofstream &oFile){
    
    if(counter!=0){
        
        buffer <<= (bufferSize - counter);
        
        BitPrinter::flushBuffer(oFile);
    }
    
    return 0;
}

/*###########################################################################*/

BitReader::BitReader(){
    
    buffer = 0x00000000;
    counter = 0;
    bufferSize = sizeof(unsigned int)*8;

}


bool BitReader::readFromFile(istream &iFile){
    
    /*Si no tengo nada en el buffer levanto un bloque*/
    if(counter == 0){
        
        iFile.read((char*)&buffer,sizeof(unsigned int));
        counter = bufferSize;
        
    }
        
    unsigned int res = 0;
    
    res = buffer & 0x80000000;
    
    if(res != 0){
        buffer <<= 1;
        counter --;
        return 1;
    }
    else{
        buffer <<= 1;
        counter --;
        return 0;
    }     
        
}
